<template>
  <div
    style="
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 16px;
    "
  >
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="图片名称">
        <a-input v-model:value="searchParams.name" placeholder="输入图片名称" allow-clear />
      </a-form-item>
      <a-form-item label="分类">
        <a-input v-model:value="searchParams.category" placeholder="输入分类" allow-clear />
      </a-form-item>
      <a-form-item label="审核状态" name="reviewStatus">
        <a-select
          v-model:value="searchParams.reviewStatus"
          :options="PIC_REVIEW_STATUS_OPTIONS"
          placeholder="请输入审核状态"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>

    <a-space>
      <a-button type="primary" @click="doCreate">
        <template #icon>
          <plus-outlined />
        </template>
        创建图片
      </a-button>
      <a-button type="primary" @click="doBatchCreate">
        <template #icon>
          <plus-outlined />
        </template>
        批量创建图片
      </a-button>
    </a-space>
  </div>

  <a-table
    :columns="columns"
    :data-source="dataList"
    :pagination="pagination"
    :scroll="{ x: 1650 }"
    @change="doTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'url'">
        <a-image :src="record.url" :width="120" />
      </template>
      <template v-else-if="column.dataIndex === 'tags'">
        <a-space v-if="Array.isArray(record.tags)">
          <a-tag v-for="(tag, index) in record.tags" :key="index" color="blue">{{ tag }}</a-tag>
        </a-space>
      </template>
      <template v-else-if="column.dataIndex === 'picInfo'">
        <div v-if="record.picFormat" style="line-height: 1.8">
          <div><strong>格式：</strong>{{ record.picFormat }}</div>
          <div><strong>宽度：</strong>{{ record.picWidth }}</div>
          <div><strong>高度：</strong>{{ record.picHeight }}</div>
          <div><strong>宽高比：</strong>{{ record.picScale }}</div>
          <div><strong>大小：</strong>{{ formatFileSize(record.picSize) }}</div>
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'reviewMessage'">
        <div>
          审核状态：{{
            PIC_REVIEW_STATUS_MAP[record.reviewStatus as keyof typeof PIC_REVIEW_STATUS_MAP]
          }}
        </div>
        <div>审核信息：{{ record.reviewMessage }}</div>
        <div>审核人：{{ record.reviewerId }}</div>
      </template>
      <template v-else-if="column.dataIndex === 'createTime'">
        {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template v-else-if="column.dataIndex === 'editTime'">
        {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space wrap>
          <a-button
            v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
            type="link"
            @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
          >
            通过
          </a-button>
          <a-button
            v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
            type="link"
            danger
            @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
          >
            拒绝
          </a-button>
          <a-button type="link" @click="doEdit(record.id)">编辑</a-button>
          <a-button type="link" danger @click="doDelete(record.id)">删除</a-button>
        </a-space>
      </template>
    </template>
  </a-table>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import {
  deletePictureUsingPost,
  doPictureReviewUsingPost,
  listPictureByPageUsingPost,
} from '@/api/pictureController'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import {
  PIC_REVIEW_STATUS_ENUM,
  PIC_REVIEW_STATUS_MAP,
  PIC_REVIEW_STATUS_OPTIONS,
} from '../../constants/picture'
import { PlusOutlined } from '@ant-design/icons-vue'

const router = useRouter()

// 格式化文件大小
const formatFileSize = (size: number | string | undefined): string => {
  if (!size) return '-'
  const sizeNum = typeof size === 'string' ? parseInt(size) : size
  if (sizeNum < 1024) {
    return sizeNum + 'B'
  } else if (sizeNum < 1024 * 1024) {
    return (sizeNum / 1024).toFixed(2) + 'KB'
  } else {
    return (sizeNum / 1024 / 1024).toFixed(2) + 'MB'
  }
}

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '图片',
    dataIndex: 'url',
    width: 150,
  },
  {
    title: '名称',
    dataIndex: 'name',
    width: 120,
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    width: 200,
    ellipsis: true,
  },
  {
    title: '类型',
    dataIndex: 'category',
    width: 100,
  },
  {
    title: '标签',
    dataIndex: 'tags',
    width: 200,
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo',
    width: 180,
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80,
  },
  {
    title: '审核信息',
    dataIndex: 'reviewMessage',
    width: 200,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right',
  },
]

// 数据
const dataList = ref<API.PictureVO[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 10,
})

// 获取数据
const fetchData = async () => {
  const res = await listPictureByPageUsingPost({
    ...searchParams,
  })
  if (res.data.data) {
    // 处理数据，将 tags 从字符串转换为数组
    const records = res.data.data.records ?? []
    dataList.value = records.map((item) => {
      return {
        ...item,
        tags: item.tags ? JSON.parse(item.tags as string) : [],
      }
    }) as API.PictureVO[]
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
    locale: {
      items_per_page: '/ 页',
    },
  }
})

// 表格变化处理
const doTableChange = (page: { current: number; pageSize: number }) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}

// 创建
const doCreate = () => {
  router.push({
    path: '/add_picture',
  })
}

// 批量创建
const doBatchCreate = () => {
  router.push({
    path: '/add_picture',
    query: { tab: 'batch' },
  })
}

// 编辑
const doEdit = (id: number | string) => {
  router.push({
    path: '/add_picture',
    query: { id: String(id) }, // 确保 id 作为字符串传递
  })
}

// 删除数据
const doDelete = async (id: number | string) => {
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id } as API.DeleteRequest)
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败，' + res.data.message)
  }
}
const handleReview = async (record: API.Picture, reviewStatus: number) => {
  const reviewMessage =
    reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员操作通过' : '管理员操作拒绝'
  const res = await doPictureReviewUsingPost({
    id: record.id,
    reviewStatus,
    reviewMessage,
  })
  if (res.data.code === 0) {
    message.success('审核操作成功')
    // 重新获取列表
    fetchData()
  } else {
    message.error('审核操作失败，' + res.data.message)
  }
}
</script>
